package com.farmer.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.Product;
import com.farmer.common.result.Result;
import com.farmer.product.mapper.ProductMapper;
import com.farmer.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 农产品服务实现类
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result<?> getProductList(Integer pageNum, Integer pageSize, String category, String keyword, Integer status) {
        try {
            Page<Product> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();

            // 商品分类过滤
            if (StringUtils.hasText(category)) {
                queryWrapper.eq("category", category);
            }

            // 关键词搜索（商品名称、描述、产地）
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                    .like("name", keyword)
                    .or()
                    .like("description", keyword)
                    .or()
                    .like("origin", keyword)
                );
            }

            // 状态过滤
            if (status != null) {
                queryWrapper.eq("status", status);
            }

            // 按创建时间倒序
            queryWrapper.orderByDesc("create_time");

            Page<Product> productPage = productMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", productPage.getRecords());
            result.put("total", productPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取农产品列表成功", result);
        } catch (Exception e) {
            log.error("获取农产品列表失败：{}", e.getMessage(), e);
            return Result.error("获取农产品列表失败");
        }
    }

    @Override
    public Result<?> getProductById(Long productId) {
        try {
            if (productId == null) {
                return Result.error("商品ID不能为空");
            }

            Product product = productMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }

            return Result.success("获取商品详情成功", product);
        } catch (Exception e) {
            log.error("获取商品详情失败：{}", e.getMessage(), e);
            return Result.error("获取商品详情失败");
        }
    }
    // 添加
    @Override
    public Result<?> addProduct(Product product) {
        try {
            if (product == null) {
                return Result.error("商品信息不能为空");
            }

            // 基本验证
            if (!StringUtils.hasText(product.getName())) {
                return Result.error("商品名称不能为空");
            }
            if (!StringUtils.hasText(product.getCategory())) {
                return Result.error("商品分类不能为空");
            }
            if (product.getPrice() == null || product.getPrice().doubleValue() <= 0) {
                return Result.error("商品价格必须大于0");
            }
            if (product.getStock() == null || product.getStock() < 0) {
                return Result.error("商品库存不能小于0");
            }

            // 设置默认状态为上架
            if (product.getStatus() == null) {
                product.setStatus(1);
            }

            int result = productMapper.insert(product);
            if (result > 0) {
                log.info("添加农产品成功：{}", product.getName());
                return Result.success("添加商品成功");
            } else {
                return Result.error("添加商品失败");
            }
        } catch (Exception e) {
            log.error("添加农产品失败：{}", e.getMessage(), e);
            return Result.error("添加商品失败");
        }
    }

    @Override
    public Result<?> updateProduct(Product product) {
        try {
            if (product == null || product.getId() == null) {
                return Result.error("商品信息不能为空");
            }

            // 检查商品是否存在
            Product existProduct = productMapper.selectById(product.getId());
            if (existProduct == null) {
                return Result.error("商品不存在");
            }

            int result = productMapper.updateById(product);
            if (result > 0) {
                log.info("更新农产品成功：{}", product.getName());
                return Result.success("更新商品成功");
            } else {
                return Result.error("更新商品失败");
            }
        } catch (Exception e) {
            log.error("更新农产品失败：{}", e.getMessage(), e);
            return Result.error("更新商品失败");
        }
    }

    @Override
    public Result<?> deleteProduct(Long productId) {
        try {
            if (productId == null) {
                return Result.error("商品ID不能为空");
            }

            // 检查商品是否存在
            Product product = productMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }

            int result = productMapper.deleteById(productId);
            if (result > 0) {
                log.info("删除农产品成功：{}", product.getName());
                return Result.success("删除商品成功");
            } else {
                return Result.error("删除商品失败");
            }
        } catch (Exception e) {
            log.error("删除农产品失败：{}", e.getMessage(), e);
            return Result.error("删除商品失败");
        }
    }

    @Override
    public Result<?> updateProductStatus(Long productId, Integer status) {
        try {
            if (productId == null || status == null) {
                return Result.error("参数不能为空");
            }

            if (status != 0 && status != 1) {
                return Result.error("状态值无效");
            }

            Product product = new Product();
            product.setId(productId);
            product.setStatus(status);

            int result = productMapper.updateById(product);
            if (result > 0) {
                String statusText = status == 1 ? "上架" : "下架";
                log.info("商品{}成功，商品ID：{}", statusText, productId);
                return Result.success("商品" + statusText + "成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("更新商品状态失败：{}", e.getMessage(), e);
            return Result.error("更新商品状态失败");
        }
    }

    @Override
    public Result<?> getCategoryList() {
        try {
            // 查询所有不重复的分类
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT category");
            queryWrapper.isNotNull("category");
            queryWrapper.ne("category", "");

            List<Product> categoryList = productMapper.selectList(queryWrapper);
            
            // 提取分类名称
            List<String> categories = new ArrayList<>();
            for (Product product : categoryList) {
                if (StringUtils.hasText(product.getCategory())) {
                    categories.add(product.getCategory());
                }
            }

            // 添加一些默认分类（如果不存在）
            Set<String> categorySet = new HashSet<>(categories);
            String[] defaultCategories = {"水果", "蔬菜", "粮食", "禽蛋", "特产", "农副产品"};
            for (String defaultCategory : defaultCategories) {
                categorySet.add(defaultCategory);
            }

            List<String> result = new ArrayList<>(categorySet);
            Collections.sort(result);

            return Result.success("获取分类列表成功", result);
        } catch (Exception e) {
            log.error("获取分类列表失败：{}", e.getMessage(), e);
            return Result.error("获取分类列表失败");
        }
    }

    @Override
    public Result<?> updateStock(Long productId, Integer quantity) {
        try {
            if (productId == null || quantity == null) {
                return Result.error("参数不能为空");
            }

            // 获取当前商品信息
            Product product = productMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }

            // 计算新库存
            int newStock = product.getStock() + quantity;
            if (newStock < 0) {
                return Result.error("库存不足，无法减少" + Math.abs(quantity) + "个");
            }

            // 更新库存
            product.setStock(newStock);
            int result = productMapper.updateById(product);
            
            if (result > 0) {
                String operation = quantity > 0 ? "增加" : "减少";
                log.info("商品库存{}成功，商品：{}，数量：{}", operation, product.getName(), Math.abs(quantity));
                return Result.success("库存更新成功，当前库存：" + newStock);
            } else {
                return Result.error("库存更新失败");
            }
        } catch (Exception e) {
            log.error("更新库存失败：{}", e.getMessage(), e);
            return Result.error("更新库存失败");
        }
    }
} 